package com.lyshop.jinxiang.activitys;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;
import com.lyshop.jinxiang.R;
import com.lyshop.jinxiang.adapters.PayTypeListAdapter;
import com.lyshop.jinxiang.adapters.RechargeQuotaGridAdapter;
import com.lyshop.jinxiang.base.BaseActivity;
import com.lyshop.jinxiang.bean.GifBean;
import com.lyshop.jinxiang.bean.PayTypeBean;
import com.lyshop.jinxiang.bean.RechargeBean;
import com.lyshop.jinxiang.bean.RechargeSettingBean;
import com.lyshop.jinxiang.bean.UserInfoBean;
import com.lyshop.jinxiang.net.ActionCallbackListener;
import com.lyshop.jinxiang.utils.CustomerUtil;
import com.lyshop.jinxiang.utils.DataUtils;
import com.lyshop.jinxiang.utils.FastClickUtil;
import com.lyshop.jinxiang.utils.GlideUtils;
import com.lyshop.jinxiang.utils.InstallUtils;
import com.lyshop.jinxiang.utils.RouteUtil;
import com.lyshop.jinxiang.utils.ToastUtil;
import com.lyshop.jinxiang.view.CertificateModule;
import com.lyshop.jinxiang.view.MyDialog;
import com.zc.mychart.utils.ArithUtil;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BeforeRechargeActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener, RechargeQuotaGridAdapter.OnCheckListener {
    private TextView tv_recharge_activity;
    private TextView tv_recharge_desc;
    private Button bt_submit;
    private GridView gv_recharge_qouat;
    private ListView lv_recharge_type;
    private RechargeQuotaGridAdapter quotaGridAdapter;
    private PayTypeListAdapter typeListAdapter;
    private ImageView iv_left;
    private ImageView iv_custom_service;
    private ImageView iv_recharge_advert;
    public RechargeSettingBean mRechargeBean;
    private UserInfoBean userInfo;
    private Dialog mGiveUpDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        quotaGridAdapter = new RechargeQuotaGridAdapter(this, this);
        gv_recharge_qouat.setAdapter(quotaGridAdapter);
        typeListAdapter = new PayTypeListAdapter(this);
        lv_recharge_type.setAdapter(typeListAdapter);
        getRechargeSetting();
    }

    private void getRechargeSetting() {
        mAppAction.getPayList(new ActionCallbackListener<RechargeSettingBean>() {
            @Override
            public void onSuccess(RechargeSettingBean data) {
                mRechargeBean = data;
                initData();
            }

            @Override
            public void onFailure(String errorCode, String message) {
                ToastUtil.showToast(BeforeRechargeActivity.this, message);
            }
        });
    }

    @Override
    protected int setContentView() {
        return R.layout.activity_before_recharge;
    }

    @Override
    protected void findViews() {
        iv_left = findViewById(R.id.iv_left);
        iv_custom_service = findViewById(R.id.iv_right);
        lv_recharge_type = (ListView) findViewById(R.id.lv_recharge_type);
        gv_recharge_qouat = (GridView) findViewById(R.id.gv_recharge_qouat);
        tv_recharge_activity = (TextView) findViewById(R.id.tv_recharge_activity);
        tv_recharge_desc = (TextView) findViewById(R.id.tv_recharge_desc);
        bt_submit = (Button) findViewById(R.id.bt_submit);
        iv_recharge_advert = (ImageView) findViewById(R.id.iv_recharge_advert);
    }

    private void initData() {
        userInfo = DataUtils.getUserInfo(mContext);
        if (mRechargeBean == null || mRechargeBean.rechargeConfigs == null || mRechargeBean.rechargeConfigs.isEmpty())
            return;

        //设置活动
        GifBean gifBean = myApplication.getGifMap().get("5");
        if (isNewUser() && gifBean != null && !TextUtils.isEmpty(gifBean.img)) {
            iv_recharge_advert.setVisibility(View.VISIBLE);
            GlideUtils.showImageFitxyOptions(mContext, gifBean.img, iv_recharge_advert);
        } else {
            iv_recharge_advert.setVisibility(View.GONE);
        }


        //设置类型
        typeListAdapter.setDataSource(mRechargeBean.rechargeConfigs);
        //设置默认选中
        for (int i = 0; i < mRechargeBean.rechargeConfigs.size(); i++) {
            if (mRechargeBean.rechargeConfigs.get(i).isDefault == 1) {
                typeListAdapter.setCheckedPosition(i);
            }
        }

        //设置金额
        quotaGridAdapter.setDataSource(mRechargeBean.rechargeConfigs.get(typeListAdapter.getCheckedPosition()).rechargeAmounts);
        //设置默认选中
        quotaGridAdapter.setCheckedPosition(getCurrentPrice(mRechargeBean.rechargeConfigs.get(typeListAdapter.getCheckedPosition()).rechargeAmounts));

        //设置按钮金额
        bt_submit.setText("确认转入" + mRechargeBean.rechargeConfigs.get(typeListAdapter.getCheckedPosition()).rechargeAmounts.get(quotaGridAdapter.getCheckedPosition()).amount + "元");

        //设置活动
        if (mRechargeBean.activityLink != null && !mRechargeBean.activityLink.title.isEmpty()) {
            tv_recharge_activity.setText(mRechargeBean.activityLink.title);
            tv_recharge_activity.setVisibility(View.VISIBLE);
        } else {
            tv_recharge_activity.setVisibility(View.GONE);
        }

        tv_recharge_desc.setText(mRechargeBean.helpExplain);
    }

    @Override
    protected void setListeners() {
        iv_left.setOnClickListener(this);
        iv_custom_service.setOnClickListener(this);
        tv_recharge_activity.setOnClickListener(this);
        bt_submit.setOnClickListener(this);
        lv_recharge_type.setOnItemClickListener(this);
        iv_recharge_advert.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_submit:
                if (FastClickUtil.isFastClick()) {
                    return;
                }
                if (isUserValidLogin()) {
                    if (typeListAdapter.getList().size() - 1 < typeListAdapter.getCheckedPosition())
                        return;
                    int code = typeListAdapter.getList().get(typeListAdapter.getCheckedPosition()).code;
                    int amount = quotaGridAdapter.getList().get(quotaGridAdapter.getCheckedPosition()).amount;
                    double chooseMoney = Double.parseDouble(String.valueOf(amount));
                    double resultMoney = ArithUtil.add(chooseMoney, Double.parseDouble(String.valueOf(userInfo.money_sum)));
                    if (resultMoney > 2000 || typeListAdapter.getList().get(typeListAdapter.getCheckedPosition()).need_verification == 1) {
                        if (CertificateModule.getInstance(mContext).isCertificate(null)) {
                            doRecharge(code, amount);
                        }
                    } else {
                        doRecharge(code, amount);
                    }
                }
                break;
            case R.id.tv_recharge_activity:
                if (mRechargeBean != null)
                    RouteUtil.toWebViewActivity(this, mRechargeBean.activityLink.link);
                break;
            case R.id.iv_left:
                showGiveUpDialog();
                break;
            case R.id.iv_right:
                CustomerUtil.customerService(this);
                break;
            case R.id.iv_recharge_advert:
                RouteUtil.routePageByUrl((BaseActivity) mContext, myApplication.getGifMap().get("5").link);
                break;
            case R.id.bt_leave:
                mGiveUpDialog.dismiss();
                backActivity();
                break;
            case R.id.bt_stay:
                mGiveUpDialog.dismiss();
                break;
        }
    }

    private void doRecharge(int code, int amount) {
        if (typeListAdapter.getCheckedType() == 1) {
            //支付宝
            userRecharge(code, amount);
        } else {
            //银联
            RouteUtil.goMoneyModuleActivity(BeforeRechargeActivity.this,
                    RouteUtil.PAGE_RECHARGE, Double.valueOf(amount),
                    String.valueOf(code));
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        typeListAdapter.setCheckedPosition(i);
        PayTypeBean payTypeBean = typeListAdapter.getList().get(i);
        if (payTypeBean == null) return;
        gv_recharge_qouat.setVisibility(View.VISIBLE);
        quotaGridAdapter.setDataSource(payTypeBean.rechargeAmounts);
        quotaGridAdapter.setCheckedPosition(getCurrentPrice(payTypeBean.rechargeAmounts));
        bt_submit.setText("确认转入" + payTypeBean.rechargeAmounts.get(quotaGridAdapter.getCheckedPosition()).amount + "元");
    }

    @Override
    public void onCheckPosition(int position) {
        quotaGridAdapter.setCheckedPosition(position);
        bt_submit.setText("确认转入" + quotaGridAdapter.getList().get(quotaGridAdapter.getCheckedPosition()).amount + "元");
    }

    /**
     * 获取默认金额
     *
     * @param list
     * @return
     */
    private int getCurrentPrice(List<PayTypeBean.RechargeAmounts> list) {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).isDefault == 1) {
                return i;
            }
        }
        return 0;
    }

    /**
     * 判断是否新用户
     */
    private boolean isNewUser() {
        if (userInfo == null) return true;
        if (userInfo.money_sum > 0){
            return false;
        }
        return true;
    }

    /**
     * 支付宝支付
     */
    private void userRecharge(int code, int amount) {
        loading();
        mAppAction.userSaving(code, amount, new ActionCallbackListener<RechargeBean>() {
            @Override
            public void onSuccess(RechargeBean data) {
                cancelLoading();
                //支付宝微信支付埋点
                Map<String, Object> userMap = new HashMap<>();
                userMap.put("zfb_wx", data.url);
                MobclickAgent.onEventObject(myApplication, "ZFB_WX_PAY", userMap);

                String url = data.url;
                if (url.startsWith("http")) {
                    Uri uri = Uri.parse(url);
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    mContext.startActivity(intent);
//                    RouteUtil.toWebViewActivity(BeforeRechargeActivity.this, url);
                } else if (url.startsWith("alipay")) {
                    if (InstallUtils.checkAliPayInstalled(mContext)) {
                        try {
                            String scheme = "alipayqr://platformapi/startapp?saId=10000007&qrcode=" + URLEncoder.encode(url, "UTF-8");
                            Intent intent = Intent.parseUri(scheme, Intent.URI_INTENT_SCHEME);
                            startActivity(intent);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        ToastUtil.showToast(mContext, "请先安装支付宝");
                    }
                } else if (url.startsWith("weixin")) {
                    if (InstallUtils.isWeChatInstalled(mContext)) {
                        Uri uri = Uri.parse(url);
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        startActivity(intent);
                    } else {
                        ToastUtil.showToast(mContext, "请先安装微信");
                    }
                }
            }

            @Override
            public void onFailure(String errorCode, String message) {
                cancelLoading();
                ToastUtil.showToast(mContext, message);
            }
        });
    }

    /**
     * 充值挽留弹窗
     */
    private void showGiveUpDialog() {
        if (mGiveUpDialog == null) {
            mGiveUpDialog = new MyDialog(this, true, Gravity.BOTTOM);
            View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_give_up_recharge, null);
            Button bt_leave = (Button) view.findViewById(R.id.bt_leave);
            Button bt_stay = (Button) view.findViewById(R.id.bt_stay);
            bt_leave.setOnClickListener(this);
            bt_stay.setOnClickListener(this);
            mGiveUpDialog.setContentView(view);
        }
        mGiveUpDialog.show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == event.KEYCODE_BACK) {
            showGiveUpDialog();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
